﻿using YouWei.Winform.Common;
using YouWei.Winform.Model;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YouWei.Infrastructure.Service;

namespace YouWei.Winform
{

    /// <summary>
    /// IE浏览器
    /// </summary>
    public partial class FrmMainViolation : Form
    {
        DCVehicleViolationQueryService queryService = new DCVehicleViolationQueryService();
        DCInterfaceLogService logService = new DCInterfaceLogService();
        DiyaDistributorInterfaceService interfaceService = new DiyaDistributorInterfaceService();

        protected DCVehicleViolationQuery vehQuery = new DCVehicleViolationQuery();   //当前查询
        protected string Base122Url = "https://bj.122.gov.cn";
        protected Dictionary<string, string> ProDic = new Dictionary<string, string>();

        protected int TimerCount = 0;  //默认三次失败就是失败
        protected int ImageCount = 0;  //验证码加载错误次数 超过3次就默认识别
        protected string Capcha = "";   //当前验证码

        //cookie缓存
        protected CookieContainer ck = new CookieContainer();

        public FrmMainViolation()
        {
            InitializeComponent();
            wbRight.ScriptErrorsSuppressed = true;
            wbRight.Url = new Uri(Base122Url + "/views/inquiry.html");
        }

        #region 浏览器

        /// <summary>
        /// 重写错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            //忽略该错误并抑制错误对话框 
            e.Handled = true;
        }

        /// <summary>
        /// 获取地址
        /// </summary>
        /// <param name="url"></param>
        private void GetCookies(string url)
        {
            ck = new CookieContainer();
            string cookie = CookieReader.GetCookie(url);
            if (!string.IsNullOrEmpty(cookie))
            {
                string[] strs = cookie.Split(new char[] { ';' });
                foreach (var item in strs)
                {
                    string[] strs1 = item.Split(new char[] { '=' });
                    var cke = new Cookie(strs1[0].Trim(), strs1[1].Trim())
                    {
                        Domain = wbRight.Document.Url.Host,
                        Expired = false,
                        Expires = DateTime.Now.AddDays(1),
                        HttpOnly = true
                    };
                    ck.Add(cke);
                }
            }
        }

        #endregion

    
        /// <summary>
        /// 请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostData()
        {
            //{"message":"操作成功！","data":{"content":{"detail":0,"zs":4,"ws":0,"bs":0,"bd":4,"notLogin":true}},"code":200}
            ApiResult rt = RequestHelper.PostHtml(Base122Url + "/m/publicquery/vio", "hpzl=" + vehQuery.VehicleType + "&hphm1b=" + vehQuery.VehicleLicense.Substring(1) + "&hphm=" + vehQuery.VehicleLicense + "&fdjh=" + vehQuery.EngineCode + "&captcha=" + Capcha + "&qm=wf&page=1", Encoding.UTF8, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36", ck);
            if (rt.status == 0)
            {
                VioModel model = JsonConvert.DeserializeObject<VioModel>(rt.message);
                if (model.code == 200)
                {
                    short result = 0;
                    short.TryParse(model.data.content.ws, out result);
                    vehQuery.QueryWS = result;
                    result = 0;
                    short.TryParse(model.data.content.bs, out result);
                    vehQuery.QueryBS = result;
                    result = 0;
                    short.TryParse(model.data.content.bd, out result);
                    vehQuery.QueryBD = result;
                    result = 0;
                    short.TryParse(model.data.content.zs, out result);
                    vehQuery.QueryTotal = result;
                    vehQuery.QueryStatus = 1;
                    vehQuery.QueryEndTime = DateTime.Now;
                    vehQuery.QueryData = rt.message;
                    queryService.Update(vehQuery);

                    interfaceService.UpdateBalanceByDistributorId(vehQuery.DistributorId, "DrivingQuery/DrivingScoreQuery");
                    TimerCount = 0;
                }
                else
                {
                    if (model.message.StartsWith("图片验证码"))
                    {
                        if (TimerCount >= 2)
                        {
                            TimerCount = 0;
                            vehQuery.QueryTotal = -1;
                            vehQuery.QueryWS = -1;
                            vehQuery.QueryBD = -1;
                            vehQuery.QueryBS = -1;
                            vehQuery.QueryStatus = 2;
                            vehQuery.QueryEndTime = DateTime.Now;
                            vehQuery.QueryData = model.message;
                            queryService.Update(vehQuery);
                        }
                        else
                        {
                            TimerCount++;
                        }
                    }
                    else
                    {
                        TimerCount = 0;
                        vehQuery.QueryTotal = -1;
                        vehQuery.QueryWS = -1;
                        vehQuery.QueryBD = -1;
                        vehQuery.QueryBS = -1;
                        vehQuery.QueryStatus = 1;
                        vehQuery.QueryEndTime = DateTime.Now;
                        vehQuery.QueryData = model.message;
                        queryService.Update(vehQuery);
                    }
                }
            }
            else {
                if (TimerCount >= 3)
                {
                    TimerCount = 0;
                    vehQuery.QueryTotal = -1;
                    vehQuery.QueryWS = -1;
                    vehQuery.QueryBD = -1;
                    vehQuery.QueryBS = -1;
                    vehQuery.QueryStatus = 2;
                    vehQuery.QueryEndTime = DateTime.Now;
                    vehQuery.QueryData = "查询失败";
                    queryService.Update(vehQuery);
                }
                else
                {
                    TimerCount++;
                }
                TimerCount++;
            }
            timer2.Start();
        }

        /// <summary>
        /// 定时查询数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick_1(object sender, EventArgs e)
        {
            vehQuery = queryService.GetFirstNoRun();
            if (vehQuery != null)
            {
                timer2.Stop();
                foreach (var kvp in ProDic)
                {
                    if (vehQuery.VehicleLicense.StartsWith(kvp.Key))
                    {
                        string url = "https://" + kvp.Value + ".122.gov.cn";
                        if (url != Base122Url)
                        {
                            Base122Url = url;
                            wbRight.Url = new Uri(Base122Url);
                            break;
                        }
                        else
                        {
                            CaptchaLoad();
                            wbRight.Document.InvokeScript("_reloadImg");
                            break;
                        }
                    }
                }
            }
        }

        #region 验证码识别

        /// <summary>
        /// 验证码识别
        /// </summary>
        /// <param name="drvNo"></param>
        /// <param name="dnNo"></param>
        protected void CaptchaLoad()
        {
            string str = "";
            var rt = RequestHelper.GetFile(Base122Url + "/captcha?nocache=" + DateTime.Now.Ticks, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36", ck);
            if (rt.status == 1 && rt.bytes.Length > 0)
            {
                str = Convert.ToBase64String(rt.bytes);
            }
            else
            {
                ImageCount++;
                if (ImageCount >= 2)
                {
                    vehQuery.QueryTotal = -1;
                    vehQuery.QueryWS = -1;
                    vehQuery.QueryBD = -1;
                    vehQuery.QueryBS = -1;
                    vehQuery.QueryStatus = 2;
                    vehQuery.QueryEndTime = DateTime.Now;
                    vehQuery.QueryData = rt.message;
                    queryService.Update(vehQuery);
                }
            }
            ImageCount = 0;
            if (CaptchOCR(str))
            {
                PostData();
            }

            if (string.IsNullOrEmpty(str))
            {
                timer2.Start();
                return;
            }
            ImageCount = 0;
            //获取验证码
            if (CaptchOCR(str))
            {
                PostData();
            }
        }

        /// <summary>
        /// 验证码识别
        /// </summary>
        /// <param name="str"></param>
        private bool CaptchOCR(string str)
        {
            bool rtq = true;

            RestClient restClient = new RestClient("https://v2-api.jsdama.com")
            {
                UserAgent = UserAgentConst.GetUserAgent()
            };
            RestRequest request = new RestRequest("/upload", Method.POST);

            request.AddHeader("Host", "v2-api.jsdama.com");
            request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.AddHeader("Content-Type", "text/json");
            var model = new JsdamaModel
            {
                captchaData = str
            };
            request.AddJsonBody(model);
            IRestResponse response = null;
            try
            {
                request.AddJsonBody(model);
                response = restClient.Execute(request);

                var rt = JsonConvert.DeserializeObject<JsDamaResultModel>(response.Content);
                if (rt.code == 0)
                {
                    Capcha = rt.data.recognition;
                    //定时轮询
                    timer2.Stop();
                }
                else
                {
                    timer2.Start();
                    rtq = false;
                }
            }
            catch (Exception ex)
            {
                Error(ex, "https://v2-api.jsdama.com/upload");
                timer2.Start();
                rtq = false;
            }

            logService.Insert(new DCInterfaceLog()
            {
                APIPath = "https://v2-api.jsdama.com/upload",
                ResponseResult = response == null ? "" : response.Content,
                RequestParm = "",
                ResponseStatus = -1,
                CallSource = 5,
                RequestDate = DateTime.Now,
                ResponseDate = DateTime.Now
            });
            return rtq;
        }

        #endregion

        private void Error(Exception ex, string url)
        {
            logService.Insert(new DCInterfaceLog()
            {
                ResponseResult = ex.Message,
                RequestParm = ex.Source,
                ResponseStatus = -1,
                CallSource = 5,
                APIPath = url,
                RequestDate = DateTime.Now,
                ResponseDate = DateTime.Now
            });
        }

        private void InitDic()
        {
            ProDic.Add("京", "bj");
            ProDic.Add("津", "tj");
            ProDic.Add("冀", "he");
            ProDic.Add("晋", "sx");
            ProDic.Add("蒙", "nm");
            ProDic.Add("辽", "ln");
            ProDic.Add("吉", "jl");
            ProDic.Add("黑", "hl");
            ProDic.Add("沪", "sh");
            ProDic.Add("皖", "ah");
            ProDic.Add("闽", "fj");
            ProDic.Add("赣", "jx");
            ProDic.Add("鲁", "sd");
            ProDic.Add("豫", "ha");
            ProDic.Add("鄂", "hb");
            ProDic.Add("湘", "hn");
            ProDic.Add("粤", "gd");
            ProDic.Add("桂", "gx");
            ProDic.Add("琼", "hi");
            ProDic.Add("渝", "cq");
            ProDic.Add("川", "sc");
            ProDic.Add("贵", "gz");
            ProDic.Add("云", "yn");
            ProDic.Add("藏", "xz");
            ProDic.Add("陕", "sn");
            ProDic.Add("甘", "gs");
            ProDic.Add("青", "qh");
            ProDic.Add("宁", "nx");
            ProDic.Add("新", "xj");

            ProDic.Add("苏A", "nkg");
            ProDic.Add("苏B", "wux");
            ProDic.Add("苏C", "xuz");
            ProDic.Add("苏D", "czx");
            ProDic.Add("苏E", "szv");
            ProDic.Add("苏F", "ntg");
            ProDic.Add("苏G", "lyg");
            ProDic.Add("苏H", "has");
            ProDic.Add("苏J", "ynz");
            ProDic.Add("苏K", "yzo");
            ProDic.Add("苏L", "zhe");
            ProDic.Add("苏M", "tzs");
            ProDic.Add("苏N", "suq");

            ProDic.Add("浙A", "hgh");
            ProDic.Add("浙B", "ngb");
            ProDic.Add("浙C", "wnz");
            ProDic.Add("浙D", "jix");
            ProDic.Add("浙E", "hzh");
            ProDic.Add("浙F", "sxg");
            ProDic.Add("浙G", "jha");
            ProDic.Add("浙H", "quz");
            ProDic.Add("浙J", "zos");
            ProDic.Add("浙K", "tzz");
            ProDic.Add("浙L", "lss");
        }

        private void wbRight_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

            GetCookies(wbRight.Url.ToString());

            timer2.Start();
        }

        private void FrmMainViolation_Load(object sender, EventArgs e)
        {
            InitDic();
        }
    }
}
